package com.ipfsemc.ipfsemc.wx;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ApiUtil {

    @Autowired(required = false)
    private RequestConfig requestConfig;            /* 默认请求配置，由Apache提供 */

    /**
     * 执行 GET 请求
     *
     * @param url
     * @return 响应200返回内容，404返回null
     * @throws Exception
     */
    public String getRequest(String url, String encoding) {
        HttpGet request = new HttpGet(url);     /* 创建http GET请求 */
        request.setConfig(requestConfig);
        try {
            return doHttpRequest(request, encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 执行带有参数的GET请求
     *
     * @param url
     * @param params
     * @return 响应200返回内容，404返回null
     * @throws ClientProtocolException
     * @throws IOException
     * @throws URISyntaxException
     */
    public String getRequest(String url, Map<String, String> params, String encoding) throws Exception {
        URIBuilder builder = new URIBuilder(url);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.setParameter(entry.getKey(), entry.getValue());
        }
        return getRequest(builder.build().toString(), encoding);
    }

    /**
     * 执行HTTP Request
     *
     * @param request 请求
     * @return 状态200 返回数据，否则返回null
     * @throws Exception
     */
    public String doHttpRequest(HttpUriRequest request, String encoding) {
        CloseableHttpResponse response = null;
        try {
            response = getHttpClient().execute(request);            /* 执行请求 */
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity(), encoding);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 创建HTTP本地连接
     *
     * @return
     */
    private CloseableHttpClient getHttpClient() {
        return HttpClients.createDefault();
    }

    /**
     * 执行post请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public String postMapRequest(String url, Map<String, String> params, Map<String, String> headers, String encoding) throws Exception {
        HttpPost request = new HttpPost(url);           /* 创建http POST请求 */
        request.setConfig(requestConfig);               /* 设置默认配置信息 */
        if (null != headers && !headers.isEmpty()) {    /* 有头信息参数 */
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
        if (null != params) {
            List<NameValuePair> parameters = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }           /* 构造一个form表单式的实体 */
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, encoding);
            request.setEntity(formEntity);              /* 将请求实体设置到httpPost对象中 */
        }
        return doHttpRequest(request, encoding);
    }

    /**
     * 执行post请求
     *
     * @return
     * @throws IOException
     */
    public String postRequest(String url, Map<String, String> headers, String encoding) {
        HttpPost request = new HttpPost(url);           /* 创建http POST请求 */
        request.setConfig(requestConfig);               /* 设置默认配置信息 */
        if (null != headers && !headers.isEmpty()) {    /* 有头信息参数 */
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
        return doHttpRequest(request, encoding);
    }

    /**
     * 执行post请求
     *
     * @param url       请求地址
     * @param paramType 数据类型JSON/XML
     * @param params    请求JSON/XML字符串数据(没有设置为空即可)
     * @param headers   需要添加请求头的map(没有设置为空即可)
     * @return 响应状态200 返回数据，否则返回null
     * @throws Exception
     */
    public String postRequest(String url, String paramType, String params, Map<String, String> headers, String encoding) {
        HttpPost request = new HttpPost(url);           /* 创建http POST请求 */
        request.setConfig(requestConfig);               /* 设置默认配置 */
        if (null != headers && !headers.isEmpty()) {    /* 有头信息参数 */
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
        if ("xml".equalsIgnoreCase(paramType)) {/* 构造一个字符串的实体,并将请求实体设置到httpPost对象中 */
            request.setEntity(new StringEntity(params, ContentType.APPLICATION_XML));
        } else if ("json".equalsIgnoreCase(paramType)) {
            request.setEntity(new StringEntity(params, ContentType.APPLICATION_JSON));
        }
        return doHttpRequest(request, encoding);
    }

}
